package org.madgecko.basic.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;

public class Captcha {
	private int width;
	private int height;
	private int num = 4;
	private String code = "0123456789";
	private static final Random rand = new Random();
	private static Captcha captcha;
	
	public Captcha() {
	}

	public static Captcha getInstance(){
		if(null==captcha){
			captcha = new Captcha();
		}
		return captcha;
	}
	
	public void set(int width, int height, int num, String code){
		this.setWidth(width);
		this.setHeight(height);
		this.setNum(num);
		this.setCode(code);
	}
	
	public void set(int width, int height){
		this.setWidth(width);
		this.setHeight(height);
	}
	
	public void setWidth(int width) {
		this.width = width;
	}
	public void setHeight(int height) {
		this.height = height;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public static void setCaptcha(Captcha captcha) {
		Captcha.captcha = captcha;
	}
	
	public String generateCheckCode(){
		 StringBuffer sb = new StringBuffer();
		 for(int i=0; i<num; i++){
			 sb.append(code.charAt(rand.nextInt(code.length())));
		 }
		 return sb.toString();
	}
	
	public BufferedImage generateCheckImg(String checkCode){
		 BufferedImage img = new BufferedImage(width, height,
		 BufferedImage.TYPE_INT_RGB);
		 Graphics2D graphic = img.createGraphics();
		 graphic.setColor(Color.WHITE);
		 graphic.fillRect(0, 0, width, height);
		 graphic.setColor(Color.BLACK);
		 graphic.drawRect(0, 0, width-1, height-1);
		 Font font = new Font("Monaca", Font.BOLD+Font.ITALIC, (int)(height*0.8));
		 graphic.setFont(font);
		 for(int i=0; i<num; i++){
			 graphic.setColor(new Color(rand.nextInt(125), rand.nextInt(125), rand.nextInt(125)));
			 graphic.drawString(String.valueOf(checkCode.charAt(i)), i*(width/num)+10, (int)(height*0.8));
		 }
		 for(int i=0; i<(width+height); i++){
			 graphic.setColor(new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)));
			 graphic.drawOval(rand.nextInt(width), rand.nextInt(height), 1, 1);
		 }
		 for(int i=0; i<4; i++){
			 graphic.setColor(new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)));
			 graphic.drawLine(0, rand.nextInt(height), width, rand.nextInt(height));
		 }
		 return img;
	}
	
}
